import Vue from 'vue'
import Vuex from 'vuex'
import clone from '@/lib/clone';

Vue.use(Vuex)

const store =  new Vuex.Store({
  state: {
    recordList : [] as RecordItem[],
    tagList : [] as TagItem[],
    currentTagList : [] as TagItem[]
  },
  mutations: {
    // record store...
    getRecordList : (state) =>{
      state.recordList = JSON.parse(window.localStorage.getItem('recordList')||'[]') as RecordItem[];
    },
    createRecord : (state,record:RecordItem) => {
      const newRecord:RecordItem = clone(record);
      newRecord.createdAt = new Date().toISOString();
      state.recordList.push(newRecord);
      window.localStorage.setItem('recordList',JSON.stringify(state.recordList));
    },

    // tag store...
    saveTagList : (state) => { 
      window.localStorage.setItem('tagList',JSON.stringify(state.tagList));
    },
    getTagList : (state,type:string) => {
      state.tagList = JSON.parse(window.localStorage.getItem('tagList')||'[]') as TagItem[];
      if(state.tagList.length === 0){
        state.tagList = [{label:'生活用品',msg:'household',type:'-'},{label:'交通',msg:'commute',type:'-'},
          {label:'服饰',msg:'clothes',type:'-'},{label:'学习',msg:'study',type:'-'},
          {label:'吃饭',msg:'food',type:'-'},{label:'水电气',msg:'electricity',type:'-'},
          {label:'娱乐活动',msg:'entertainment',type:'-'}];
        store.commit('saveTagList');
      };   
      state.currentTagList = state.tagList.filter((item)=>{return item.type === type;}) as TagItem[];
    },
    createTag : (state,value:TagItem)=>{
      state.tagList.push(value);
      store.commit('saveTagList');
    },
    removeTag : (state,value:TagItem)=>{
      state.tagList.splice(state.tagList.indexOf(value),1);
      store.commit('saveTagList');
    }
  }
});

export default store;
